requirejs.config({
    baseUrl: './',
    paths: {
        "jquery": ["/common/vendor/jquery-2.1.4/jquery-2.1.4.min"],
        "base": ["/common/scripts/base"],
        "ajax": ["/common/scripts/ajax"],
        "underscore": ["/common/vendor/underscore-1.8.3/underscore.min"],
        "local": "/common/scripts/local",
        "file": ["/common/scripts/file"]
    }
});
require(["base", "jquery", "ajax", "underscore", "file", "local"], function(base, $, ajax, _, file, local) {
    "use strict";
    var account = '',
        startDate = base.getUrlParameter('startDate') || '', //开始时间
        endDate = base.getUrlParameter('endDate') || '',//结束时间
        source = base.getUrlParameter('source') || '150001',//来源
        currency = base.getUrlParameter('currency') || '401156', //币种
        dateType = base.getUrlParameter('dateType') || '03'; //币种
    var search = {
        init: function() {
            var self = this;
            if(base.isAndroid()){
                $('body').addClass('android');
            }
            TalkingData.onHTSCEvent("page","leaf304", "持仓股综合分析_搜索", "", "");
            local.read({
                P_SOURCE: "", //系统源 150001 普通 150     002 信用  150003 限售股 150000 全账户
                P_CURRENCY: "", //401156 人民币 401344  港元 401840 美元
                P_ACCOUNT:""
            }, function(_obj) {
                var str = _obj.P_CURRENCY;
                switch (str){
                    case '港币':{
                        currency = '401344';
                        break;
                    }
                    case '美元':{
                        currency = '401840';
                        break;
                    }
                    case '元':{
                        currency = '401156';
                        break;
                    }
                    default:{
                        currency = '401156';
                        break;
                    }
                }
                source = _obj.P_SOURCE;
                account = _obj.P_ACCOUNT;
                self.getChcList();
                self.bindEvent();
                $(".show-chc").height($(window).height()-$(".public-header").innerHeight());
            })
        },
        /**
         * [getChcList 获取持仓股列表]
         * @return {[type]} [description]
         */
        getChcList: function() {
            var self = this,
                url = "/reqxml?action=27401&path=/account/hold_analysis/search_list",
                params = {
                    clientNo: account,
                    token: "($Token)",
                    source: source, //来源
                    currency: currency, //币种
                    startDate: startDate,
                    endDate: endDate,
                    dateType:dateType
                };
            ajax.run(url, params, function(data) {
                if (data && data.BINDATA) {
                    var obj = JSON.parse(data.BINDATA),
                        code = obj.code,
                        msg = obj.msg;
                    if (code === "0") {
                        if (obj.data && obj.data.stockList && obj.data.stockList.length != 0) {
                            self.searchData(obj.data);
                            $('.chc-stock').html(self.renderHtml(obj.data.stockList));
                        }
                    } else {
                        msg = msg && msg != '' ? msg : "接口返回错误"
                        alert(msg);
                    }
                } else {
                    alert("接口返回错误");
                }
            }, function(obj) {
                var msg = obj.ERRORMESSAGE && obj.ERRORMESSAGE != '' ? obj.ERRORMESSAGE : "网络错误";
                alert(msg);
            });
        },
        /**
         * [searchData 将所有数据处理成搜索需要的数据格式]
         * @param  {[type]} 全部持仓数据 [description]
         * @return {[type]}      [description]
         */
        searchData: function(data) {
            var search = [];
            _.each(data.stockList, function(item) {
                var list = [],
                    marketType = { //沪a 4353 沪b 4354 深a 4609 深b 4610 创业板 4619 沪基金 4356 深基金 4612 沪债券 4355 深债券 4611 沪指数 4366 深指数 4622
                        '4353': '沪A',
                        '4354': '沪B',
                        '4609': '深A',
                        '4610': '深B',
                        '4619': '创业板',
                        '4356': '沪基金',
                        '4612': '深基金',
                        '4355': '沪债券',
                        '4611': '深债券',
                        '4614': '中小板'
                    };;
                list[0] = item.marketCode;
                list[1] = item.stockName;
                list[2] = item.stockCode;
                list[3] = item.marketType;
                list[4] = item.simpleEnglish;
                list[5] = item.source;
                search.push(list);
            })
            file.insert("positon-search.js", { stockList: search });
        },
        /**
         * [search description]
         * @param  {[type]} key [description]
         * @return {[type]}     [description]
         */
        search: function(key) {
            var self = this,
                searchList = [];
            file.readByKey("positon-search.js", 'stockList', function(data) {
                base.log(data);
                _.each(data, function(item) {
                    var obj = [item[1],item[2],item[4]];
                    if (obj.toString().indexOf(key) >= 0) {
                        var searchObj = {};
                        searchObj.marketCode = item[0];
                        searchObj.stockName = item[1];
                        searchObj.marketType = item[3]
                        searchObj.stockCode = item[2];
                        searchObj.simpleEnglish = item[4];
                        searchObj.source = item[5];
                        searchList.push(searchObj);
                    }
                })
                if (searchList.length != 0) {
                    $('.chc-stock').hide();
                    $('.search-list').html(self.renderHtml(searchList)).show();
                } else {
                    $('.chc-stock').hide();
                    $('.search-list').html('');
                    if(key.length < 15){
                        self.toast('在此期间内，您暂无该只股票持仓');
                    }
                }

            })
        },
        /**
         * [renderHtml 渲染页面]
         * @param  {[type]} list [页面数据]
         * @return {[type]}      [description]
         */
        renderHtml: function(list) {
            var html = '';
            _.each(list, function(item) {
                html = html +
                    '<li data-source="'+item.source+'"data-marketcode="'+item.marketCode+'">' +
                    '<div class="stock-type" ><span>' + (item.marketType || '--') + '</span></div>' +
                    '<div class="stock-code">' + (item.stockCode || '--') + '</div>' +
                    '<div class="stock-name">' + (item.stockName || '--');
                if(item.source == '150002'){
                    html  = html + '<i class="icon-rong"></i>'
                }
                html = html + '</div></li>';
            });
            return html;
        },
        /**
         * [toast 显示文字]
         * @param  {[type]} str [description]
         * @return {[type]}     [description]
         */
        toast: function(str) {
            if($(".toast").css('display') == 'none'){
                $(".toast").html(str).fadeIn();
                setTimeout(function() {
                    $(".toast").fadeOut();
                }, 1000);
            }
        },
        /**
         * [bindEvent 事件绑定]
         * @return {[type]} [description]
         */
        bindEvent: function() {
            var self = this;
            //输入框 keyup 事件
            //$('#stock-code').keyup(function() {
            $('#stock-code').bind('input',function() {
                TalkingData.onHTSCEvent("click","leaf304", "持仓股综合分析_搜索", "", "请输入股票代码");
                var val = $(this).val();
                if (val === '') {
                    $('.chc-stock').show();
                    $('.search-list').hide();
                    $('.icon-delete').addClass('hide');
                } else {
                    if(base.isIOS()){
                        var reg = new RegExp('^[0-9\u4e00-\u9fa5]+$');
                        if(reg.test(val)){
                            self.search(val.toUpperCase());
                        }
                        $('.icon-delete').removeClass('hide');
                    }else{
                        self.search(val.toUpperCase());
                        $('.icon-delete').removeClass('hide');
                    }
                    
                }
            });
            //输入框 清空输入文字
            $('.icon-delete').click(function() {
                $('#stock-code').val("");
                $('.select-list').html('');
                $('.icon-delete').addClass('hide');
                $('.search-list').hide();//隐藏搜索列表
                $('.chc-stock').show();
            });
            $('.chc-stock,.search-list').on('click','li',function(){
                var name = $.trim($(this).find('.stock-name').text()),
                    code = $.trim($(this).find('.stock-code').html()),
                    marketCode = $.trim($(this).attr('data-marketcode')),
                    source = $.trim($(this).data('source')),
                    isFouse = source === "150002" ? true : false;
                base.href('http://action:10061/?type=9&&topcolor=F64843&&fullscreen=1&&url=/zlcftajax/information/position/stockDetail.htm?source='+source+'&currency='+currency+'&startDate='+startDate+'&endDate='+endDate+'&stockName='+encodeURIComponent(name)+'&stockCode='+code+'&marketCode='+marketCode+'&isFouse='+isFouse);
                var sourceDis = source == "150002" ? "融资融券" : "普通交易";
                TalkingData.onHTSCEvent("click","leaf304", "持仓股综合分析_搜索", "", "持仓股详情|zh="+sourceDis+"|code="+code+"|name="+name);
            })
        }
    }
    search.init();
});